package com.jaychen.spring.context;

import com.jaychen.spring.factory.config.AbstractBeanFactory;
import com.jaychen.spring.factory.config.AutowireCapableBeanFactory;
import com.jaychen.spring.core.io.loader.ResourceLoader;
import com.jaychen.spring.core.ioc.BeanDefinition;
import com.jaychen.spring.core.ioc.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * @Author Jay Chen
 * @Date 2020/11/10 12:47
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {

    private String location;

    public ClassPathXmlApplicationContext(String location) throws Exception {
        this(location, new AutowireCapableBeanFactory());
    }

    public ClassPathXmlApplicationContext(String location, AbstractBeanFactory beanFactory) throws Exception {
        super(beanFactory);
        this.location = location;
        refresh();
    }

    @Override
    void refresh() throws Exception {
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
        xmlBeanDefinitionReader.loadBeanDefinitions(location);
        for (Map.Entry<String, BeanDefinition> entry : xmlBeanDefinitionReader.getRegistry().entrySet()) {
            // 将所有加载的bean注入到beanDefinitionMap中（提前暴漏所有的bean）。在get bean时在具体初始化bean
            beanFactory.registerBeanDefinition(entry.getKey(), entry.getValue());
        }
    }
}
